require 'ostruct'

class CreditCalc
	#Валюта кредиту
	attr_accessor :currency
	
	#Сумма кредиту                             СК
	attr_accessor :summa
	
	#Відсоткова ставка %
	attr_accessor :interest_rate
	
	#Строк кредитування, місяці      t
	attr_accessor :months
	
	#Схема погашення
	# - Стандарт
	# - Ануїтет
	attr_accessor :redemption
	
	#Додаткова комісія  %
	attr_accessor :commission
	
	#Спосіб нарахування
	# - На початкову суму
	# - На залишок
	attr_accessor :extra_charge
	
	attr_accessor :lines
	
	def initialize(options={})
		@lines = []
		@redemption = "standart" # or annuity
		@currency = options.delete(:currency) if options[:currency]
		@summa = options.delete(:summa).to_f if options[:summa]
		@interest_rate = options.delete(:interest_rate).to_f if options[:interest_rate]
		@months = options.delete(:months).to_i if options[:months]

		@redemption = options.delete(:redemption).to_sym if options[:redemption]
		@commission = options.delete(:commission).to_f if options[:commission]
		@extra_charge = options.delete(:extra_charge).to_sym if options[:extra_charge]
	end
	
	def valid?
		[(@months > 0),
		 (@summa > 0),
		 (@interest_rate > 0 && @interest_rate < 100),
		 (@commission >= 0)
		].all?
	end
	
	def calculate
		@lines = []
		return false unless valid?
		_interest_rate = @interest_rate.to_f / 100
		_commission = @commission.to_f / 100
		if @redemption.to_sym == :standart
			i = 1
			last_sum = 0
			dp = @summa * ((_interest_rate/12)/(1- ((1+_interest_rate/12)**(-@months)) ))
			@months.times do
      	line = OpenStruct.new
        line.month = i
        line.h = (@summa - last_sum).to_f
        line.g = @summa / @months
        line.i = (line.h * _interest_rate) / 12
        line.j = _commission * @summa
        line.k = line.g + line.i
        line.l = line.k + line.j
        @lines << line
        last_sum += line.g
        i += 1
			end
		elsif @redemption.to_sym == :annuity
			i = 1
			last_sum = 0
			ap = @summa * ((_interest_rate/12)/(1- ((1+_interest_rate/12)**(-@months)) ))
			@months.times do
      	line = OpenStruct.new
        line.month = i
        line.k = ap
        line.h = (@summa - last_sum).to_f
        line.i = (line.h * _interest_rate) / 12
        line.g = line.k - line.i
        line.j = _commission * @summa
        line.l = line.k + line.j
        i += 1
        last_sum += line.g
        @lines << line
			end
		end
		@lines
	end
	
	def sum(param)
		@lines.map(&param.to_sym).sum
	end
	
end
